<template>
	<div class="app-container">
		<el-row :gutter="15">
			<el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="150px" label-position="left">
				<el-col :span="15"><el-input v-model="formData.id" type="hidden"></el-input></el-col>
				<el-col :span="15">
					<el-form-item label="商品名称" prop="goodName">
						<el-input v-model="formData.goodName" placeholder="请输入商品名称" clearable :style="{ width: '100%' }"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="15">
					<el-form-item label="商品编号" prop="goodNo">
						<el-input v-model="formData.goodNo" placeholder="请输入商品编号" clearable :style="{ width: '100%' }"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="15">
					<el-form-item label="商品库存" prop="goodStock">
						<el-input v-model="formData.goodStock" :disabled="true" :style="{ width: '100%' }"></el-input><a href="javascript:;" @click="toPurchase">去进货<i class="el-icon-link"></i></a>
						<span style="color: red;">
							库存仅可通过进货更新							
						</span>
					</el-form-item>
				</el-col>
				<el-col :span="15">
					<el-form-item label="商品排序" prop="sort"><el-input type="number" v-model="formData.sort" :style="{ width: '100%' }"></el-input></el-form-item>
				</el-col>
				<el-col :span="15">
					<el-form-item label="商品类型" prop="categoryId">
						<el-cascader :props="props" v-model="formData.categoryIdPathArr" filterable @change="handleItemChange"></el-cascader>
					</el-form-item>
				</el-col>
				<el-col :span="15">
					<el-form-item label="商品状态" prop="isSale" required>
						<el-switch
							v-model="formData.isSale"
							active-text="上架"
							inactive-text="下架"
							active-color="#0992E7"
							@change="handleSaleSwitch"
							:inactive-value="0"
							:active-value="1"
						></el-switch>
					</el-form-item>
				</el-col>
				<el-col :span="15">
					<el-form-item label="商品售价" prop="goodPrice">
						<el-input v-model="formData.goodPrice" placeholder="请输入商品售价" clearable :style="{ width: '100%' }"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="22">
					<el-form-item label="上传商品主图" prop="mainImage">
						<el-upload
							class="avatar-uploader"
							action=""
							:show-file-list="false"
							:on-success="handleAvatarSuccess"
							:http-request="uploadAction"
							:before-upload="beforeAvatarUpload"
						>
							<img v-if="formData.mainImage" :src="formData.mainImage" class="avatar" />
							<i v-else class="el-icon-plus avatar-uploader-icon"></i>
						</el-upload>
					</el-form-item>
				</el-col>
				<el-col :span="22">
					<el-form-item label="上传商品轮播图">
						<el-upload action="" 
						list-type="picture-card" 
						:http-request="uploadCarouselAction" 
						:auto-upload="true" 
						:limit="6">
							<i slot="default" class="el-icon-plus"></i>
							<div slot="file" slot-scope="{ file }">
								<img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
								<span class="el-upload-list__item-actions">
									<span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)"><i class="el-icon-zoom-in"></i></span>
									<span v-if="!disabled" class="el-upload-list__item-delete" @click="handlePictureCardRemove(file)"><i class="el-icon-delete"></i></span>
								</span>
							</div>
						</el-upload>
						<el-dialog :visible.sync="dialogVisible"><img width="100%" :src="dialogImageUrl" alt="" /></el-dialog>
					</el-form-item>
				</el-col>
				<el-col :span="15">
					<el-form-item label="商品描述" >
						<el-input v-model="formData.goodDesc" placeholder="请输入商品描述"  type="textarea" clearable :style="{ width: '100%' }"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item size="large">
						<el-button type="primary" @click="submitForm">提交</el-button>
						<el-button @click="resetForm">重置</el-button>
					</el-form-item>
				</el-col>
			</el-form>
		</el-row>
	</div>
</template>
<script>
import axios from 'axios';
let id = 0;
let id2 = 0;
import { add, update, upload ,get} from '@/api/good';
import { getByPid } from '@/api/category';
export default {
	components: {},
	props: [],
	data() {
		return {
			props: {
				lazy: true,
				lazyLoad(node, resolve) {
					const { level } = node;
					let pid;
					if (level !== 0) {
						pid = node.value;
					}
					getByPid({ id: pid }).then(res => {
						console.log(res);
						res = res.data;
						if (res.code === 200) {
							const nodes = res.data.categoryList.map((value, i) => ({
								value: value.id,
								label: value.name,
								leaf: value.image != null
							}));
							resolve(nodes);
						}
					});
				}
			},
			formData: {
				categoryId: 0,
				categoryIdPath: '',
				goodDesc: '',
				goodName: '',
				goodNo: '',
				categoryIdPathArr: [],
				goodPrice: 0,
				id: '',
				image: '',
				isDeleted: 0,
				isSale: 0,
				mainImage: '',
				sort: 0,
				images:""
			},
			rules: {
				goodName: [
					{
						required: true,
						trigger: 'blur',
						message: '商品名称不能为空'
					}
				],
				sort: [],
				goodPrice: [
					{
						required: true,
						message: '请输入商品价格',
						trigger: 'blur'
					}
				]
			},
			dialogImageUrl: '',
			dialogVisible: false,
			disabled: false,
			imageArr:[] // 轮播图图片
		};
	},
	computed: {},
	watch: {},
	created() {
		console.log(this.$route.query)
		
		let id = this.$route.query.id;
		if(id != null)
		this.getGoodDetail(Number(id))
	},
	mounted() {},
	onLoad(option){
		
	},
	methods: {
		getGoodDetail(id){
			let that = this;
			this.$store.dispatch('good/get',id).then(res => {
				console.log(res)
				that.formData = res.data
				that.imageArr = JSON.parse(res.data.images)
				console.log(that.imageArr)
				that.formData.categoryIdPathArr = res.data.categoryIdPath.split('_').map(Number);
			});
		},
		getDefaultCategory() {},
		//
		handleItemChange(val) {
			let arr = val;
			this.formData.categoryId = arr[arr.length - 1];
			let str = arr[0];
			for (let i = 1; i < arr.length; i++) {
				str = str + '_' + arr['' + i + ''];
			}
			this.formData.categoryIdPath = str;
		},
		// 去进货
		toPurchase() {
			this.$router.push({ path: '/purchase/purchase' });
		},
		// 商品状态
		handleSaleSwitch(e) {
			console.log(e);
		},
		submitForm() {
			let that = this;
			this.$refs['elForm'].validate(valid => {
				if (!valid) return;
				console.log(this.formData);
				let api = '';
				if (this.formData.id !== '') {
					api = 'good/update';
				} else {
					api = 'good/add';
				}
				this.formData.images = JSON.stringify(this.imageArr)
				this.$store.dispatch(api, this.formData).then(res => {
					if (res.code === 200) {
						this.$message({
							message: '操作成功,1秒后跳转商品列表',
							type: 'success'
						});
						setTimeout(function() {
							that.$router.push({ path: '/good/index' });
						}, 1000);
					} else {
						this.$message({
							message: res.message,
							type: 'error'
						});
					}
				});
			});
		},
		resetForm() {
			this.$refs['elForm'].resetFields();
		},
		// 主图上传
		uploadAction(file) {
			let that = this;
			const formData = new FormData();
			formData.append('file', file.file);
			this.$store.dispatch('good/upload', formData).then(res => {
				console.log(res);
				if (res.code == 200) {
					that.formData.mainImage = res.data.imgUrl;
					that.$message.success('图片上传成功');
				} else {
					that.$message.success('图片上传失败');
				}
			});
		},
		handleAvatarSuccess(res, file) {
			this.imageUrl = URL.createObjectURL(file.raw);
		},
		beforeAvatarUpload(file) {
			const isJPG = file.type === 'image/jpeg';
			const isLt2M = file.size / 1024 / 1024 < 2;

			if (!isJPG) {
				this.$message.error('上传头像图片只能是 JPG 格式!');
			}
			if (!isLt2M) {
				this.$message.error('上传头像图片大小不能超过 2MB!');
			}
			return isJPG && isLt2M;
		},
		handleRemove(file, fileList) {
			console.log(file, fileList);
		},
		handlePreview(file) {
			console.log(file);
		},
		// 轮播图上传
		uploadCarouselAction(file) {
			let that = this;
			const formData = new FormData();
			formData.append('file', file.file);
			this.$store.dispatch('good/upload', formData).then(res => {
				console.log(res);
				if (res.code == 200) {
					that.$message.success('图片上传成功');
					that.imageArr.push(res.data)
					
				} else {
					that.$message.success('图片上传失败');
				}
			});
		},
		handlePictureCardRemove(file) {
			console.log(file);
		},
		handlePictureCardPreview(file) {
			this.dialogImageUrl = file.url;
			this.dialogVisible = true;
		}
	}
};
</script>
<style>
.toPurchase {
	text-decoration: 1px solid !important;
}
.el-upload__tip {
	line-height: 1.2;
}
.avatar-uploader .el-upload {
	border: 1px dashed #d9d9d9;
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
}
.avatar-uploader .el-upload:hover {
	border-color: #409eff;
}
.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 148px;
	height: 148px;
	line-height: 148px;
	text-align: center;
}
.avatar {
	width: 148px;
	height: 148px;
	display: block;
}
</style>
